//
//  VistaContactanos.m
//  Pico y placa
//
//  Created by Mario Franco on 1/18/13.
//  Copyright (c) 2013 Mario Franco. All rights reserved.
//

#import "VistaContactanos.h"

@interface VistaContactanos ()
{
    UILabel *lblLoading;
    UIImageView *imagenLoading;
    UIActivityIndicatorView *spinner;
}

@end

@implementation VistaContactanos
@synthesize txtMensaje;
@synthesize btnEnviar;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    btnEnviar.enabled = NO;
    [txtMensaje setUserInteractionEnabled:YES];
    
    CGRect lblLoadingRect;
    
    //Es iPhone
    if(self.view.frame.size.width == 320)
    {
        int y=-1;
        //Es iPhone 5
        if(CGSizeEqualToSize([[UIScreen mainScreen] preferredMode].size,CGSizeMake(640, 1136)))
            y=250;
        
        //Es otro iPhone
        else
            y=210;
        
        lblLoadingRect = CGRectMake(65, y, 200, 35);
        lblLoading = [[UILabel alloc] initWithFrame:lblLoadingRect];
        
    }
    
    //Es iPad
    else
    {
        lblLoadingRect = CGRectMake(221, 459, 327, 54);
        lblLoading = [[UILabel alloc] initWithFrame:lblLoadingRect];
    }
    
    [lblLoading setFont:[UIFont fontWithName:@"ArialMT" size:18.0]];
    [lblLoading setBackgroundColor:[UIColor clearColor]];
    lblLoading.textColor = [UIColor whiteColor];
    lblLoading.textAlignment = NSTextAlignmentCenter;

    lblLoading.text = @"Enviando mensaje...";
    lblLoading.alpha = 0;
    
    CGRect imagenLoadingRect = CGRectMake(0,0,self.view.frame.size.width, self.view.frame.size.height);
    imagenLoading = [[UIImageView alloc] initWithFrame:imagenLoadingRect];
    
    //Es iPhone
    if(self.view.frame.size.width == 320)
        imagenLoading.image = [UIImage imageNamed:@"waitOverLay.png"];
    
    //Es iPad
    else
        imagenLoading.image = [UIImage imageNamed:@"waitOverLayiPad.png"];
    
    [self.view addSubview:imagenLoading];
    imagenLoading.alpha = 0;
    [imagenLoading addSubview:lblLoading];
}


- (void)viewWillAppear:(BOOL)animated
{
    [txtMensaje becomeFirstResponder];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)descartarVista:(id)sender
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (IBAction)enviarCorreo:(id)sender
{
    btnEnviar.enabled = NO;
    // create soft wait overlay so the user knows whats going on in the background.
    [self createWaitOverlay];
    
    //the guts of the message.
    SKPSMTPMessage *testMsg = [[SKPSMTPMessage alloc] init];
    testMsg.fromEmail = @"idemovil1@gmail.com";
    testMsg.toEmail = @"pypcolombia@idemovil.com";
    testMsg.relayHost = @"smtp.gmail.com";
    testMsg.requiresAuth = YES;
    testMsg.login = @"idemovil1@gmail.com";
    testMsg.pass = @"uniandes";
    testMsg.subject = @"Mensaje de usurio P&P Colombia iOS";
    testMsg.wantsSecure = YES; // smtp.gmail.com doesn't work without TLS!
    
    // Only do this for self-signed certs!
    // testMsg.validateSSLChain = NO;
    testMsg.delegate = self;
    
    //email contents
    NSString * bodyMessage = txtMensaje.text;
    
    NSDictionary *plainPart = [NSDictionary dictionaryWithObjectsAndKeys:@"text/plain",kSKPSMTPPartContentTypeKey,
                               bodyMessage ,kSKPSMTPPartMessageKey,@"8bit",kSKPSMTPPartContentTransferEncodingKey,nil];
    
    testMsg.parts = [NSArray arrayWithObjects:plainPart,nil];
    [testMsg send];
}

- (void)messageSent:(SKPSMTPMessage *)message
{
    [self removeWaitOverlay];
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Mensaje enviado" message:@"Gracias por tu colaboración" delegate:self cancelButtonTitle:@"Aceptar" otherButtonTitles: nil];
    [alert show];
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)messageFailed:(SKPSMTPMessage *)message error:(NSError *)error
{
    btnEnviar.enabled = YES;
    [self removeWaitOverlay];
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"No se puede enviar el mensaje ¿Estás conectado a internet?" delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
	[alert show];
    [txtMensaje setUserInteractionEnabled:YES];
    [txtMensaje becomeFirstResponder];
}

-(void)createWaitOverlay
{
    [txtMensaje setUserInteractionEnabled:NO];
    // fade the overlay in
    [UIView beginAnimations: @"Fade In" context:nil];
    [UIView setAnimationDelay:0];
    [UIView setAnimationDuration:.5];
    imagenLoading.alpha = 1;
    lblLoading.alpha = 1;
    [UIView commitAnimations];
    [self startSpinner];
}

-(void)removeWaitOverlay
{
    //fade the overlay out
    [UIView beginAnimations: @"Fade Out" context:nil];
    [UIView setAnimationDelay:0];
    [UIView setAnimationDuration:.5];
    imagenLoading.alpha = 0;
    lblLoading.alpha = 0;
    [UIView commitAnimations];
    [self stopSpinner];
}

-(void)startSpinner
{
    spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    spinner.hidden = FALSE;
    
    //Es iPhone
    if(self.view.frame.size.width == 320)
    {
        int y=-1;
        //Es iPhone 5
        if(CGSizeEqualToSize([[UIScreen mainScreen] preferredMode].size,CGSizeMake(640, 1136)))
            y=200;
        
        //Es otro iPhone
        else
            y=160;
        spinner.frame = CGRectMake(137, y, 50, 50);
    }
    
    //Es iPad
    else
    {
        spinner.frame = CGRectMake(359, 420, 50, 50);
    }
    
    [spinner setHidesWhenStopped:YES];
    [self.view addSubview:spinner];
    [self.view bringSubviewToFront:spinner];
    [spinner startAnimating];
}

-(void)stopSpinner
{
    [spinner stopAnimating];
    [spinner removeFromSuperview];
}

-(void)willPresentAlertView:(UIAlertView *)alertView
{
    for (UIView *view in alertView.subviews)
    {
        // change the background image
        if ([view isKindOfClass:[UIImageView class]])
        {
            UIImage *theImage = [UIImage imageNamed:@"fondoAlerta.png"];
            ((UIImageView *)view).image = [theImage resizableImageWithCapInsets:UIEdgeInsetsMake(49, 8, 8, 8)];
        }
    }
}

-(void)textViewDidChange:(UITextView *)textView
{
    if ([txtMensaje.text length]==0 )
        btnEnviar.enabled = NO;
    else
        btnEnviar.enabled = YES;
}

@end
